﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using Underrun.Helpers;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.Tcp;
using Underrun.DAL;

namespace Underrun
{
    public partial class AORNUnderrun : ServiceBase
    {
        public AORNUnderrun()
        {
            InitializeComponent();
        }

        public void OnDebug()
        {
            OnStart(null);
        }

        protected override void OnStart(string[] args)
        {
            StartAutoFunction();
            StartManualFunction();
        }

        private void StartAutoFunction()
        {
            EndlessTimer endlessTimer = new EndlessTimer();
            //endlessTimer.LoopFunction += new EventHandler(EndlessTimerLoopFunction);
            //endlessTimer.StartEndlessTimer();
        }

        private void StartManualFunction()
        {
            const int port = 1234;
            ChannelServices.RegisterChannel(new TcpChannel(port), false);
            WellKnownObjectMode mode = WellKnownObjectMode.SingleCall;
            RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(AppDAL), "AppDAL", mode);
            Console.WriteLine("SEVER is starting with PORT= {0}", port);
            Console.ReadLine();
        }

        protected override void OnStop()
        {
            System.IO.File.Create(AppDomain.CurrentDomain.BaseDirectory + "OnStop.txt");

            int port = 1234;
            ChannelServices.RegisterChannel(new TcpChannel(port), false);
            WellKnownObjectMode mode = WellKnownObjectMode.SingleCall;
            RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(AppDAL), "AppDAL", mode);
            Console.WriteLine("SEVER was stopped with PORT= {0}", port);
            Console.ReadLine();
        }

        void EndlessTimerLoopFunction(object sender, EventArgs e)
        {
            System.IO.File.Create(AppDomain.CurrentDomain.BaseDirectory + "OnStart" + SingleTon.ObjSingle.Temp.ToString(CultureInfo.InvariantCulture) + ".txt");
            
            //User user = new User();
            //user.Id = Guid.NewGuid();
            //user.Code = "tlu1000" + SingleTon.ObjSingle.Temp.ToString(CultureInfo.InvariantCulture);
            //user.FirstName = "thang";
            //user.LastName = "thang";
            //user.Email = "thang";

            //db.Users.InsertOnSubmit(user);
            //db.SubmitChanges();
        }
    }
}
